package giit.computerbase.dao;

/**
 * This class is for connection database<br>
 * User: tum0r
 * Package Name: giit.computerbase.dao
 * Time: 2018/10/28 Sunday 18:00:29
 */

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

public abstract class SQL {

    protected Connection connection = null;
    protected PreparedStatement preparedStatement = null;
    protected ResultSet resultSet = null;

    public abstract boolean open(String host, int port, String dabaseName, String encode, String userName, String password);


    private void init(String command, Object[] args) throws SQLException {
        preparedStatement = connection.prepareStatement(command);
        if (args != null) {
            for (int index = 0; index < args.length; index++) {
                preparedStatement.setObject(index + 1, args[index]);
            }
        }
    }

    public boolean update(String command, Object[] args) {
        try {
            init(command, args);
            preparedStatement.executeUpdate();
            return true;
        } catch (SQLException e) {
            System.out.println(command);
            e.printStackTrace();
        }
        return false;
    }

    public boolean add(String command, Object[] args) {
        return update(command, args);
    }

    public boolean delete(String command, Object[] args) {
        return update(command, args);
    }

    public ArrayList<HashMap<String, Object>> query(String command, Object[] args) {
        ArrayList<HashMap<String, Object>> result = new ArrayList<>();
        HashMap<String, Object> temp = new HashMap<>();
        try {
            init(command, args);
            resultSet = preparedStatement.executeQuery();
            int count = resultSet.getMetaData().getColumnCount();
            while (resultSet.next()) {
                temp = new HashMap<>();
                for (int index = 1; index <= count; index++) {
                    temp.put(resultSet.getMetaData().getColumnName(index), resultSet.getObject(index));
                }
                result.add(temp);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    public boolean alter(String command, Object[] args) {
        return update(command, args);
    }

    public void close() throws SQLException {
        if (resultSet != null) {
            resultSet.close();
        }
        if (preparedStatement != null) {
            preparedStatement.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}
